package com.sdd.rpi_mobile.resourceLists;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;

import com.sdd.rpi_mobile.infoTypes.PlacesInfoActivity;

/** Implements ListViewLoader interface for a list filled with lists */
public class ListListLoader implements ListViewLoader 
{
	private Context mContext;

	ListListLoader(Context c) {
		this.mContext = c;
	}

	@Override
	public ArrayAdapter<String> getArrayAdapter(int resId) {

		final Resources res = this.mContext.getResources();

		//Obtain string array based on placeId
		TypedArray typedArray = res.obtainTypedArray(resId);
		int n = typedArray.length();
		
		String[] array = new String[n];
		final String[] items = new String[n];

		for (int i = 0; i < n; ++i) {
			int id = typedArray.getResourceId(i,0);
			
			if (id > 0) {
				array = res.getStringArray(id);
				items[i] = array[0];
			} 
			else {
				Log.e("major error", "Something is wrong with the xml file or resource in ListItemLoader");
			}
		}
		
		//It is important to recycle.
		typedArray.recycle();

		ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this.mContext, 
				android.R.layout.simple_list_item_1, items);
		
		return arrayAdapter;
	}

	@Override
	public Intent getIntent(Context context, int resId, int pos) {
		Bundle bundle = new Bundle();
		Resources res = this.mContext.getResources();		
		
		TypedArray typedArray = res.obtainTypedArray(resId); // Obtain string array based on placeId		
		int arrayId = typedArray.getResourceId(pos,0);
		
		bundle.putInt("resource", arrayId);
		
		String[] itemArray = res.getStringArray(arrayId);
		typedArray.recycle();
		
		Intent intent = null;
		
		if(itemArray.length > 3){
			intent = new Intent(this.mContext, PlacesInfoActivity.class);
		}
		else {
			//Get array id, instead string item
			typedArray = res.obtainTypedArray(arrayId);
			arrayId = typedArray.getResourceId(1, 0);
			typedArray.recycle();
			
			bundle.putInt("resource", arrayId);	
			intent = new Intent(this.mContext, ListActivity.class);
		}
		
		intent.putExtras(bundle);
		return intent;
	}
}